﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Data;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Xml;

namespace XmlDemo
{
    public partial class CmbProCity : UserControl
    {
        XmlDocument myXml = new XmlDocument();
        public CmbProCity()
        {
            InitializeComponent();
            
        }
        protected override void OnCreateControl()
        {
            base.OnCreateControl();
            if (!this.DesignMode)
            {
                myXml.Load("Area.xml");//读取指定的xml文件
                GetProvince();
                cmbCity.SelectedIndexChanged += new EventHandler(cmbCity_SelectedIndexChanged);
                cmbCountry.DropDownStyle = ComboBoxStyle.DropDown;
            }
        }
        private void GetProvince()
        {
            XmlNodeList xmls = myXml.SelectSingleNode("address").ChildNodes;
            foreach (XmlNode xmlNode in xmls)
            {
                XmlElement xe = xmlNode as XmlElement;
                cmbProvince.Items.Add(xe.GetAttribute("name"));
            }
        }
        private void GetCity(string province)
        {
            cmbCity.Items.Clear();
            XmlNode xmls = myXml.SelectSingleNode("*/province[@name='" + province + "']");
            foreach (XmlNode xmlNode in xmls.ChildNodes)
            {
                XmlElement xe = xmlNode as XmlElement;
                cmbCity.Items.Add(xe.GetAttribute("name"));
            }
        }
        private void GetCountry(string city)
        {
            cmbCountry.Items.Clear();
            XmlNode xmls = myXml.SelectSingleNode("*/province[@name='" + cmbProvince.Text + "']/*[@name='" + city + "']");
            foreach (XmlNode xmlNode in xmls.ChildNodes)
            {
                XmlElement xe = xmlNode as XmlElement;
                cmbCountry.Items.Add(xe.GetAttribute("name"));
            }
        }
        private void cmbProvince_SelectedIndexChanged(object sender, EventArgs e)
        {
            cmbCity.Text = string.Empty;
            GetCity(cmbProvince.Text);
        }

        void cmbCity_SelectedIndexChanged(object sender, EventArgs e)
        {
            cmbCountry.Text = string.Empty;
            GetCountry(cmbCity.Text);
        }

        public ComboBoxStyle DropDownStyle { get; set; }

        private void button1_Click(object sender, EventArgs e)
        {
            XmlNode xmnd = myXml.SelectSingleNode("*/province[@name='" + this.cmbProvince.Text + "']");
            AddElement(xmnd);
        }
        private void AddElement(XmlNode xmlNode)
        {
            XmlWrite xmlEdit = new XmlWrite();
            xmlEdit.XmlNode = xmlNode;
            xmlEdit.MyXml = this.myXml;
            xmlEdit.ShowDialog();
        }
    }
}
